<template>
  <div class="board-head px-4">
    <div class="flex justify-between items-center h-full" style="height: 42px">
      <div class="flex">
        <div class="flex items-center">
          <div class="text-nowrap">{{ t["名称"] }}</div>
          <a-input v-model="themForm.themeName" allow-clear> </a-input>
          <a-divider direction="vertical"></a-divider>
          <a-button class="text-nowrap" type="primary" @click="visible = true">
            {{ t["背景"] }}
          </a-button>
        </div>
      </div>
      <div class="flex gap-2">
        <a-button size="mini" @click="close">{{ t["取消"] }}</a-button>
        <a-button size="mini" type="primary" :loading="loading" @click="save">
          {{ t["保存"] }}
        </a-button>
      </div>
    </div>
  </div>
  <FileSelector v-model:visible="visible" @change="selectPic"></FileSelector>
</template>

<script setup lang="ts">
import { Library } from "@/api/service/library/types";
import { createTheme, updateTheme } from "@/api/service/theme/theme";

import FileSelector from "@/views/admin/components/file-selector/FileSelector.vue";

import { list } from "../../data/curd";
import { resetForm, showBoard, themForm } from "../../data/form";
import { componentList } from "../data/data";

const loading = ref(false);
const t = translate("公共模块");
const visible = ref(false);

const close = async () => {
  resetForm();
  await list();
  showBoard.value = false;
};
const save = async () => {
  loading.value = true;
  try {
    if (themForm.value.category instanceof Array) {
      themForm.value.category = themForm.value.category.join(",");
    }

    const data = {
      ...themForm.value,
      image: componentList.value
    };
    if (!themForm.value.themeId) {
      await createTheme(data);
    } else {
      await updateTheme(data);
    }
    await close();
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
};

const selectPic = (item: Library[]) => {
  themForm.value.background = item[0].uri;
};
</script>

<style lang="scss" scoped>
.board-head {
  height: 48px;
  flex-basis: 48px;
}
</style>
